package guet.dream.servlet;

import guet.dream.category.Category;
import guet.dream.category.CategoryDao;
import guet.dream.category.CategoryDaoImpl;
import guet.dream.category.CategoryService;

import java.io.IOException;
import java.io.Writer;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TreeView
 */
public class TreeViewServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	CategoryDao categoryDao = new CategoryDaoImpl();
		Set<Category> categories = categoryDao.findMainCategories();
		
		request.setAttribute("categories", categories);
		
		RequestDispatcher view = request.getRequestDispatcher("/treeview.jsp");
		view.forward(request, response);
		

	}


	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 CategoryDao categoryDao = new CategoryDaoImpl();  
		 Category category ;
		 int count = 0;
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
		
		   String operation = request.getParameter("flag");
		   String message;
           
		   if(operation.equals("remove")){
			   int id = Integer.valueOf(request.getParameter("id"));
			  count = categoryDao.remove(id);
			    if(count == 1){
			    	message = "所选类型已经被成功删除";
			    }else{
			    	message = "类型删除失败";
			    }
			   
			   
		   }else if(operation.equals("edit")){
			   int id = Integer.valueOf(request.getParameter("id"));
			   String name = request.getParameter("name");
			   String desc = request.getParameter("desc");
			   
			   category = new Category(id,name,desc);
			   count = categoryDao.update(category);
			    if(count == 1){
			    	message = "所编辑类型更新成功";
			    }else{
			    	message = "类型编辑更新失败";
			    }
			   
		   }else if(operation.equals("create")){
			   String name = request.getParameter("name");
			   String desc = request.getParameter("desc");
			   int parentId = Integer.valueOf(request.getParameter("parentId"));
			   
			   category = new Category(1000000,name,desc);
			   count = categoryDao.save(category,parentId);
			    if(count == 1){
			    	message = "添加新类型成功.";
			    }else{
			    	message = "新类型添加失败";
			    }   
		   }else{
			   message = "操作非法!";
		   }
		   
		   Writer out = response.getWriter();
		   out.write(message);
		   out.flush();
	}

}
